package com.maoslv.aop;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;

@Component
@Aspect // 切面 定义了通知和切点的关系
@Slf4j
public class LogAspect {

    @Pointcut("@annotation(com.maoslv.aop.LogAnnotation)")
    public void pointcut() {}

    // 环绕通知
    @Around("pointcut()")
    public Object log(ProceedingJoinPoint joinPoint) throws Throwable {
        // 开始时间
        long startTime = System.currentTimeMillis();
        // 执行方法
        Object result = joinPoint.proceed();

        // 结束时间
        long endTime = System.currentTimeMillis();
        // 执行时长
        long time = endTime - startTime;

        recordLog(joinPoint, startTime, endTime, time);
        return result;
    }

    private void recordLog(ProceedingJoinPoint joinPoint, long startTime, long endTime, long time) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        LogAnnotation annotation = method.getAnnotation(LogAnnotation.class);
        log.info("======================请求内容======================");
        log.info("操作：{}", annotation.operator());

        // 请求的类名和方法名
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = signature.getName();
        log.info("请求的类名：{}", className);
        log.info("请求的方法名：{}", methodName);

        // 请求的参数
        log.info("请求的参数：{}", joinPoint.getArgs().length == 0 ? "空" : Arrays.toString(joinPoint.getArgs()));

        // 请求的IP
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        log.info("请求IP：{}", request.getRemoteAddr());
        log.info("请求地址：{}", request.getRequestURI());

        // 请求时间
        log.info("开始时间：{}", new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(new Date(startTime)));
        log.info("结束时间：{}", new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(new Date(endTime)));
        log.info("执行时长：{}ms", time);

        log.info("===================================================\n");
    }
}
